package com.xyazm.order.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.xyazm.order.domain.dto.CancelOrderAssembleDTO;
import com.xyazm.order.domain.param.CancelOrderAssembleParam;
import com.xyazm.order.mapstruct.OrderApiMapstruct;
import com.xyazm.order.service.IAfterSaleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 监听 取消订单/超时未支付取消 前置准备工作 消息 ok
 * @Author: xuyou
 * @Date: 2022/7/1 10:03
 */
@Slf4j
@Component
public class CancelRefundListener implements MessageListenerConcurrently {

    @Autowired
    private IAfterSaleService orderAfterSaleService;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                String message = new String(messageExt.getBody());
                log.info("CancelRefundListener message:{}", message);
                CancelOrderAssembleDTO cancelOrderAssembleDTO = JSONObject.parseObject(message,
                        CancelOrderAssembleDTO.class);
                CancelOrderAssembleParam cancelOrderAssembleParam =
                        OrderApiMapstruct.INSTANCE.convertCancelOrderAssembleParam(cancelOrderAssembleDTO);
                // 执行退款前的准备操作前的操作 (计算金额、记录售后信息等准备工作)
                orderAfterSaleService.processCancelOrder(cancelOrderAssembleParam);
                log.info("执行退款前的准备操作处理完成");
            }
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        } catch (Exception e) {
            log.error("CancelRefundListener error", e);
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
    }
}
